﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace LibTracker
{
    public class DataInput
    {
        public string TrackNumber { get; set; }
        public int CountryDestanationID { get; set; }
    }

    public class TrakNumbers
    {
        private string path = @"XML\services.xml";
        delegate ResultRequestFromPostService GetRecordsFromPostServicesDelegate();
        //blic IEnumerable<PostRecord> GetRecordsFromPostServices()

        struct ResultAsync
        {
            public IAsyncResult AsyncRes;
            public GetRecordsFromPostServicesDelegate Delegate;
        }


        public IList<ResultRequestFromPostService> CheckTrackNumbers(IEnumerable<DataInput> aListOfTrackNumbers)
        {
            Debug.WriteLine("Вошли в главный метод");
            
            IList<ResultRequestFromPostService> result = new List<ResultRequestFromPostService>();
            
            IList<ManualResetEvent> doneEvents = new List<ManualResetEvent>();
            IList<ResultAsync> listAsyncRes = new List<ResultAsync>();
            Debug.WriteLine("Начинаем перебирать трэк номера");
            foreach (var element in aListOfTrackNumbers)
            {
                var number = element.TrackNumber;
                var id = element.CountryDestanationID;
                ManualResetEvent doneEvent = new ManualResetEvent(false);
                doneEvents.Add(doneEvent);
                TrackNumber trackNumber = new TrackNumber(new XMLDataSet(number, id.ToString(), path), doneEvent);
                GetRecordsFromPostServicesDelegate psd = trackNumber.GetRecordsFromPostServices;
                Debug.WriteLine("Запускаем на выполнение поток");
                IAsyncResult asyncRes = psd.BeginInvoke(null, null);
                listAsyncRes.Add(new ResultAsync() { AsyncRes = asyncRes, Delegate = psd });
                //int res = sd.EndInvoke(asyncRes);

            }

            Debug.WriteLine("Ожидаем завершения всех потоков");
            WaitHandle.WaitAll(doneEvents.ToArray());
            Debug.WriteLine("Получаем результаты из потоков");
            foreach (ResultAsync resultAsync in listAsyncRes)
            {
                ResultRequestFromPostService res = resultAsync.Delegate.EndInvoke(resultAsync.AsyncRes);
                result.Add(res);
            }



            return result;
        }



    }
}
